<template>
  <div class="app-role">
    <el-row>
      <el-col :span="24">
        <dynForm :info-form="infoForm" :search-tags="searchTags">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="doSearch"
          >
            {{ $t("search") }}</el-button
            >
        </dynForm>
      </el-col>
    </el-row>
    <div class="table-buttons">
      <el-button
        v-btnPermission:add
        type="primary"
        icon="el-icon-plus"
        @click="switchHandle('add')"
      >{{ $t("add") }}</el-button
      >
      <el-button
        v-btnPermission:edit
        :disabled="UpdateDisabled"
        type="primary"
        icon="el-icon-edit"
        @click="switchHandle('modify')"
      >{{ $t("modify") }}</el-button
      >
      <el-button
        v-btnPermission:delete
        :disabled="DeleteDisabled"
        type="danger"
        icon="el-icon-delete"
        @click="switchHandle('del')"
      >{{ $t("delete") }}</el-button
      >
    </div>
    <!-- 主体部分 -->
    <el-card class="box-card" shadow="never">
      <!-- 表单部分 -->
      <el-row :gutter="15">
        <el-col
          :xs="24"
          :sm="24"
          :md="16"
          :lg="16"
          :xl="17"
          style="margin-bottom: 10px"
        >
          <dynTable
            ref="dynTable"
            :loading="tableLoading"
            :table-data="tableData"
            :table-columns="tableColumns"
            :handle-selection-change="handleSelectionChange"
            :row-click="rowClick"
          />
          <!--分页组件-->
          <pagination
            :total="total"
            :page.sync="listQuery.page"
            :size.sync="listQuery.size"
            @pagination="getList"
          />
        </el-col>
        <!-- 菜单授权 -->
        <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
          <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
              <el-tooltip
                :content="$t('assigmentRole')"
                class="item"
                effect="dark"
                placement="top"
              >
                <span style="float: left; padding: 6px 9px; fontSize: 14px">{{ $t("menuAssignment") }}</span>
              </el-tooltip>
              <el-button
                :disabled="!showButton"
                :loading="menuLoading"
                icon="el-icon-check"
                style="float: right; padding: 6px 9px"
                type="primary"
                @click="saveMenu"
              >{{ $t("save") }}</el-button>
            </div>
            <el-tree
              ref="menu"
              :data="menus"
              :default-checked-keys="menuIds"
              :props="defaultProps"
              accordion
              show-checkbox
              node-key="id"
            />
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    <!--表单渲染-->
    <!-- 弹窗组件 -->
    <myDialog
      ref="myDialog"
      :form="form"
      :title="title"
      :is-disabled="isDisabled"
      @doSave="doSave"
      @closeDialog="closeDialog"
    />
  </div>
</template>

<script>
import crudRoles from '@/api/system/role'
import { getMenusTree } from '@/api/system/menu'
import eHeader from '../../components/header'
import myDialog from './module/form'
import mySetting from '@/mixins/mySetting'
import { clearNull } from '@/utils/myTools'

export default {
  name: 'RolePage',
  components: { eHeader, myDialog },
  mixins: [mySetting],
  data() {
    return {
      defaultProps: { children: 'children', label: 'label', isLeaf: 'leaf' },
      menuLoading: false,
      showButton: false,
      menus: [],
      menuIds: [],
      multipleSelection: [],
      UpdateDisabled: true,
      DeleteDisabled: true,
      title: '', // 弹窗标题
      form: {},
      infoForm: {},
      searchTags: [
        { label: this.$t('keyword'), prop: 'name', tag: 'DynInput' }
      ],
      isDisabled: false, // 是否禁用表单内容
      tableColumns: [
        { prop: '', label: '', type: 'selection' },
        { prop: '', label: this.$t('index'), type: 'index', width: '50px', templete: (_scope) => {
          return (
            <span>{ (this.listQuery.page - 1) * this.listQuery.size + _scope.$index + 1 }</span>
          )
        } },
        {
          prop: 'roleName',
          label: this.$t('roleName')
        },
        {
          prop: 'description',
          label: this.$t('roleDesc')
        },
        {
          prop: 'createTime',
          label: this.$t('createTime'),
          width: 165
        }
      ],
      tableLoading: true
    }
  },
  created() {
    this.initList()
    this.initTreetable()
  },
  methods: {
    switchHandle(val) {
      switch (val) {
        case 'add':
          this.handleClickAdd()
          break
        case 'del':
          this.handleDel()
          break
        case 'modify':
          this.modify()
          break
        default:
          break
      }
    },
    // 新增数据
    handleClickAdd() {
      this.title = this.$t('add')
      this.$refs.myDialog.openDialog()
    },
    // 删除数据
    handleDel() {
      this.$confirm(
        this.$t('confirmDelete') +
          this.multipleSelection.length +
          this.$t('recordCount'),
        this.$t('tip'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      ).then(() => {
        const ids = this.multipleSelection.map(v => v.id)
        crudRoles.del({ ids: ids }).then((res) => {
          this.$betterTips(res, this.setOnePage, this.initList)
        })
      })
    },
    // 修改数据
    // 不想动了, 懒的动了
    modify() {
      this.title = this.$t('modify')
      this.isDisabled = false
      crudRoles.get({ id: this.multipleSelection[0].id }).then((res) => {
        this.form = res.data
      })
      this.$refs.myDialog.openDialog()
    },
    // 切换分页
    getList(val) {
      this.options.loading = true
      this.listQuery = val
      this.initList()
    },
    // 初始化列表
    initList() {
      let obj = {
        ...this.listQuery,
        ...this.infoForm
      }
      obj = clearNull(obj)
      crudRoles.getList(obj).then((res) => {
        this.tableData = res.data
        this.total = res.total
        this.tableLoading = false
      })
    },
    // 点击查询
    doSearch() {
      this.listQuery.page = 1
      this.initList()
    },
    // 确认新增
    doSave() {
      this.listQuery.page = 1
      this.initList()
    },
    handleSelectionChange(row) {
      this.multipleSelection = row
    },
    rowClick(row) {
      this.$refs.dynTable.$refs.multipleTable.clearSelection()
      this.$refs.dynTable.$refs.multipleTable.toggleRowSelection(row)
      this.handleCurrentChange(row)
    },
    // 关闭弹窗清空数据
    closeDialog() {
      this.isDisabled = false
      this.form = {}
    },
    initTreetable() {
      getMenusTree({ pid: 0 }).then(res => {
        this.menus = res.data
      })
    },
    // 触发单选
    handleCurrentChange(row) {
      this.$refs.menu.setCheckedKeys([])
      crudRoles.getMenuIdsByRoleId({ roleid: row.id }).then((res) => {
        const checked = res.data.filter(v => !v.isHalf).map(c => c.id)
        this.menuIds = checked
      })
      this.showButton = true
    },
    // 保存菜单
    saveMenu() {
      this.menuLoading = true
      const halfs = this.$refs.menu.getHalfCheckedKeys().map(v => ({ id: v, isHalf: 1 }))
      const menus = this.$refs.menu.getCheckedKeys().map(v => ({ id: v, isHalf: 0 }))
      crudRoles.editMenu({ id: this.multipleSelection[0].id, menus: [...halfs, ...menus] }).then((res) => {
        this.menuLoading = false
        this.$betterTips(res)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/defaultStyle.scss";
.app-role {
  padding-bottom: 33px;
}
.app-role .el-row:nth-child(1) {
  padding-bottom: 0;
}
</style>
